<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2019-01-03 20:14:16
 * @Description: 栏目管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-21 18:43:00
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Content/CateController.php
 */

namespace App\Http\Controllers\Console\Content;

use App\Customize\Func;
use App\Exceptions\FireFlyException;
use App\Models\Content\Cate;
use Illuminate\Http\Request;
use App\Models\Content\Article;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Content\CateRelation;
use App\Http\Requests\Cms\CategoryRequest;
use App\Http\Requests\Cms\CategoryUpdateRequest;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\SortRequest;

class CateController extends Controller
{
    public function getSelect()
    {
        $cates = DB::table('cms_category')->leftJoin('cms_cate_relation',function($q){
            $q->on('cms_category.id','=','cms_cate_relation.descendant')->where('cms_cate_relation.distance',1);
        })->select('id','cms_cate_relation.ancestor as parent_id','name','sort','url')->get();
        $data = array_map(function ($q) {
            return (array) $q;
        }, $cates->toArray());
        $select = Func::toTreeSelect($data);
        $result[] = ['id' => 0, 'parent_id' => 0, 'title' => "一级栏目", 'value' => 0, 'expand' => true, 'selected' => false, 'checked' => false];
        $result = array_merge($result, $select);
        return $this->resJson(200,'成功',$result);
    }
    public function getList(Request $request){
        $all = DB::table('cms_category')->leftJoin('cms_cate_relation',function($q){
            $q->on('cms_category.id','=','cms_cate_relation.descendant')->where('cms_cate_relation.distance',1);
        })->select('id','cms_cate_relation.ancestor as parent_id','name','type','link_flag','sort')->orderBy('sort','asc')->orderBy('id','asc')->get();
        $tree = $this->toTree($all,'0');
        return $this->resJson(200,'成功', $tree);
    }
    private function toTree($data, $pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach ($data as $v) {
                if ($v->parent_id == $pid) {
                    $v = ['id' => $v->id, 'name' => $v->name,'type' => $v->type,'link_flag' => $v->link_flag, 'sort' => $v->sort, '_showChildren' => true];
                    $v['children'] = $this->toTree($data, $v['id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    public function postCreate(CategoryRequest $request){
        $data = $request->all();
        DB::transaction(function() use($data){
            $create = ['name' => $data['name'], 'thumb' => $data['thumb'], 'title' => $data['title'], 'keyword' => $data['keyword'], 'description' => $data['description'], 'content' => $data['content'], 'link_flag' => $data['link_flag'], 'cate_tpl' => $data['cate_tpl'], 'art_tpl' => $data['art_tpl'], 'display' => $data['display'], 'type' => $data['type'], 'sort' => $data['sort']];
            if ($data['link_flag'] == 1) $create['url'] = $data['url'];
            $detail = Cate::create($create);
            $this->updateRelation($detail->id,$data['parent_id']);
        });
        return $this->resJson(200,'成功');
    }
    public function getDetail(DetailRequest $request){
        $detail_id = $request->input('detail_id');
        $detail = DB::table('cms_category')->leftJoin('cms_cate_relation',function($q){
            $q->on('cms_category.id','=','cms_cate_relation.descendant')->where('cms_cate_relation.distance',1);
        })->select('cms_category.*','cms_cate_relation.ancestor as parent_id')->where('id',$detail_id)->first();
        return $this->resJson(200,'成功', $detail);
    }
    public function postEdit(CategoryUpdateRequest $request){
        $data = $request->all();
        if($data['parent_id'] == $data['detail_id']){
            throw new FireFlyException(403,'父栏目不能选择自己');
        }
        DB::transaction(function() use($data){
            $update = ['name' => $data['name'], 'thumb' => $data['thumb'], 'title' => $data['title'], 'keyword' => $data['keyword'], 'description' => $data['description'], 'content' => $data['content'], 'link_flag' => $data['link_flag'], 'cate_tpl' => $data['cate_tpl'], 'art_tpl' => $data['art_tpl'], 'display' => $data['display'], 'type' => $data['type'], 'sort' => $data['sort']];
            if ($data['link_flag'] == 1) $update['url'] = $data['url'];
            Cate::where('id', $data['detail_id'])->update($update);
            CateRelation::where('descendant',$data['detail_id'])->delete();
            $this->updateRelation($data['detail_id'],$data['parent_id']);
        });
        return $this->resJson(200,'成功');
    }
    // 自引用
    private function updateRelation($cate_id,$ancestor){
        $agent_relation = [];
        $agent_relation[] = ['ancestor' => $cate_id, 'descendant' => $cate_id, 'distance' => 0];
        // 如果上级不是0，找到上级的所有父级
        if ($ancestor != 0) {
            $all_relation = CateRelation::where('descendant', $ancestor)->orderBy('distance','desc')->get();
            if ($all_relation->count() > 0) {
                foreach ($all_relation as $v) {
                    $agent_relation[] = ['ancestor' => $v->ancestor, 'descendant' => $cate_id, 'distance' => $v->distance + 1];
                }
            }
        }else{
            $agent_relation[] = ['ancestor' => 0, 'descendant' => $cate_id, 'distance' => 1];
        }
        CateRelation::insert($agent_relation);
    }
    public function postRemove(DetailRequest $request){
        $detail_id = $request->input('detail_id');
        // 先找出所有子栏目，再判断子栏目中是否有文章，如果有文章，返回错误
        $childs = CateRelation::where('ancestor', $detail_id)->pluck('descendant');
        // 所有子栏目ID转换为集合，查看是否含有文章或者专题
        if(Article::whereIn('cate_id',$childs)->where('del_flag',0)->count()) {
            throw new FireFlyException(403,'请检查栏目及子栏目下是否有文章或文章');
        }
        DB::transaction(function() use($childs){
            Cate::destroy($childs);
            CateRelation::whereIn('descendant',$childs)->delete();
        });
        return $this->resJson(200,'成功');
    }
    public function postSort(SortRequest $request)
    {
        Cate::where('id', $request->input('detail_id'))->update(['sort'=> $request->input('sort')]);
        return $this->resJson(200,'成功');
    }
}
